$(init);
var copyData = null;
var myType = '';
function init() {

    $('body').on('click', 'ons-tab#ac-all', function () { initAllList(-1) })
             .on('click', 'ons-tab#ac-operate', function () { initAllList(0) })
             .on('click', 'ons-tab#ac-deliver', function () { initAllList(10) })
             .on('click', 'ons-tab#ac-comment', function () { initAllList(20) })
             .on('click', 'ons-tab#ac-check', function () { initAllList(30) })
             .on('click', 'ons-tab#ac-complete', function () { initAllList(70) })
             .on('click', 'ons-tab#order-detail-tab', function () { initAllList(-1);initAllList(0);initAllList(10);initAllList(20);initAllList(30); initAllList(70);})
             .on('click', 'ons-card.ac-card .ac-card-cnt', doCardDetail)
             .on('click', 'ons-button#operate-btn', function () {submitOperate();})
             .on('click', 'button#operate-check-btn', operateCheck)
             .on('click', 'button#operate-clear-btn', operateClear);
    addCardBtnListen();
}

// Re 催款
// Op 操作
// Cm 评价
// Bk 退单
// Ap 申诉

function addCardBtnListen() {
    $('body').on('click', 'button.re-btn', doRe)
             .on('click', 'button.op-btn', doOp)
             .on('click', 'button.cm-btn', doCm)
             .on('click', 'button.bk-btn', doBk)
             .on('click', 'button.ap-btn', doAp);
}

function doOp() {
    navPushPage('/mobile-views/_detail/_card/card-operate.html');
    id = $(this).parent('.ac-card-btm').parent('.ac-card').data('id');
    tid = $(this).parent('.ac-card-btm').parent('.ac-card').data('tid');
    url = '/buyertask/buyer_task/'+ id;
    var obj = {
        taskkeyid: tid,
    }
    var url1 = url;
    var url2 = [URL_BUY_TASKDETAIL, encodeQuery(obj)].join('?');
    promiseWhen('GET', '/mobile-tmpl/card-operate-render.tmpl', url1, url2, null, renderOperate);
}

function renderOperate(r, e1, e2) {
    var ret1 = e1;
    var ret2 = e2;
    ret1.data.imgPrefix = IMG_PREFIX;
    myType = ret2.data.mainType;
    var v = ret2.data.taskkeyType.split('');

    $.inArray('2', v)!==-1? ret2.data.f2 = true : ret2.data.f2 = false;
    $.inArray('3', v)!==-1? ret2.data.f3 = true : ret2.data.f3 = false;
    $.inArray('4', v)!==-1? ret2.data.f4 = true : ret2.data.f4 = false;


    var ret = {
        e1: ret1.data,
        e2: ret2.data
    };

    copyData = ret;

    $('ons-page#card-operate div.page__content').html('');
    $('ons-page#card-operate div.page__content').append($.templates(r).render(ret, rdHelper));
}

function operateCheck() {
    console.log('check');
    console.log(copyData);
    var data = {
        buyTaskId: id,
        shopName: $('#name-area').val()
    };
    promise('get', URL_BUY_CHECK_SHOP , data, cbCheckShop, null);
}

function operateClear() {
    $('#name-area').val('');
    notifyToast('请重新输入名称核对！');
}

function submitOperate() {
    var flag = 1;
    $('input.ons-upload').each(function () {
        if(typeof($(this).attr('picurl')) === 'undefined') {
            notifyInfo('请上传截图！');
            flag = 0;
            return false;
        }
    });

    if(!flag) return;

    if($('#order-id').length > 0 && $('#order-id').val() === '') {
        notifyInfo('请输入订单编号！');
        return;
    }

    if($('#pay-money').length > 0 && $('#pay-money').val() === '') {
        notifyInfo('请输入实付金额！');
        return;
    }

    var data = {
        buyerTaskId: id,
        result: $('#i-s-result input').attr('picurl'),
        goods1: $('#i-r-goods1 input').attr('picurl'),
        goods2: $('#i-r-goods2 input').attr('picurl'),
        head:   $('#i-s-head input').attr('picurl'),
        ask:    $('#i-s-ask input').attr('picurl'),
        detail: $('#i-s-detail input').attr('picurl'),
        cart:   (myType==='pay')?$('#i-s-cart input').attr('picurl'):$('#i-add-cart input').attr('picurl'),
        talk:   $('#i-s-talk input').attr('picurl'),
        pay:    $('#i-s-pay input').attr('picurl'),
        bottom:    $('#i-s-tail input').attr('picurl'),
        shopgoods1: $('#i-s-goods1 input').attr('picurl'),
        shopgoods2:   $('#i-s-goods2 input').attr('picurl'),
        followShop:   $('#i-f-shop input').attr('picurl'),
        followGoods:  $('#i-f-goods input').attr('picurl'),
        orderid:    $('#order-id').val(),
        paymoney:   $('#pay-money').val(),
        shopname:   $('#shop-name').val()
    };

    promise('post', URL_BUY_SUBMIT_ORDER , JSON.stringify(data), cbSubmitBuy, null);
}

function cbSubmitBuy() {
    notifyInfo(MSG_SUBMIT_BUY_CORRECT);
    navPopPage();
    initAllList(0);
}

function cbCheckShop(e) {
    notifyInfo(MSG_SHOPNAME_CORRECT);
    $('ons-button#operate-btn').css('display', 'inline-block');

}

function doCm() {
    navPushPage('/mobile-views/_detail/_card/card-comment.html');
    tid = $(this).parent('.ac-card-btm').parent('.ac-card').data('tid');
    id = $(this).parent('.ac-card-btm').parent('.ac-card').data('id');
    var obj = {
        taskkeyid: tid,
    }
    $('body').on('click', 'ons-button#comment-btn', function () {
        submitComment(id);
    });
    promiseTmpl('GET', '/mobile-tmpl/card-comment-render.tmpl', [URL_BUY_TASKDETAIL, encodeQuery(obj)].join('?'), null, cbCm);
}

function cbCm(r, e) {
    var ret = e.data.taskkeyInfo;
    $('ons-page#card-comment div.page__content').html('');
    $('ons-page#card-comment div.page__content').append($.templates(r).render(ret, rdHelper));
}

function submitComment(id) {
    var data = {
        buyerTaskId: id,
        expressPicture: $("#u-express-picture input").attr('picurl'),
        goodsEvaluate: $("#u-goods-evaluate input").attr('picurl'),
        expressEvaluate: $("#u-express-evaluate input").attr('picurl')
    };
    promise('post', URL_BUY_TASK_EVALUATE , JSON.stringify(data), cbSubmitEval, null)
}

function cbSubmitEval() {
    notifyToast(MSG_EVALUATE_SUCC);
    navPopPage();
    initAllList(20);
}

function doBk() {
    console.log('bk');
    var id = $(this).parent('.ac-card-btm').parent('.ac-card').data('id');
    ons.notification.confirm({
        message: "确认取消本任务?",
        callback: function (idx) {
            switch (idx) {
                case 0:
                    break;
                case 1:
                    var obj = {
                        buyerTaskId: id
                    };
                    console.log(obj);
                    promise('GET',[URL_BUY_CANCEL_TASK, encodeQuery(obj)].join('?') ,null, cbCancelTask, null);
                    break;
            }
        }
    });
}

function cbCancelTask(e)  {
    notifyInfo('退单成功！');
    initAllList(0);
}


function doRe() {
    var obj = {
        id: $(this).parent('.ac-card-btm').parent('.ac-card').data('id')
    };
    promise('POST','/buyertask/press_money', JSON.stringify(obj), cbRe, null);
}

function doAp() {
    navPushPage('/mobile-views/_detail/_card/card-appeal.html');
    id = $(this).parent('.ac-card-btm').parent('.ac-card').data('id');
    $('body').on('click', 'ons-button#ap-btn', function () {
        submitAppel(id);
    });
}

function submitAppel(id) {
    var data = {
        buyerTaskId: id,
        type: document.querySelector('ons-select').value,
        complainContent: $('#complainContent').val(),
        picture1: $("#u-express-picture1 input").attr('picurl'),
        picture2: $("#u-express-picture2 input").attr('picurl'),
        picture3: $("#u-express-picture3 input").attr('picurl'),
	    picture4: $("#u-express-picture4 input").attr('picurl'),
	    picture5: $("#u-express-picture5 input").attr('picurl')
    };

    if(typeof(data.picture1) === 'undefined' && typeof(data.picture2) === 'undefined' && typeof(data.picture3) === 'undefined' && typeof(data.picture4) === 'undefined' && typeof(data.picture5) === 'undefined' ){
        notifyInfo('至少提交一张申诉截图！');
        return;
    }

    if(data.complainContent === '' || data.complainContent === null) {
        notifyInfo('申诉内容不能为空！');
        return;
    }else{
        promise('post', '/submit_complain' , JSON.stringify(data), cbSubmitEval, null);
    }
}

function cbSubmitEval() {
    notifyToast('提交申诉成功');
    navPopPage();
    initAllList(-1);initAllList(0);initAllList(10);initAllList(20);initAllList(30); initAllList(70);
}


function cbRe() {
    notifyToast('催款成功！请等待商家返款');
}

function doCardDetail() {
    navPushPage('/mobile-views/_detail/_card/card-detail.html');
    id = $(this).parent('.ac-card').data('id');
    url = '/buyertask/buyer_task/'+ id;
    promiseTmpl('GET', '/mobile-tmpl/card-detail-render.tmpl', url, null, cbCardDetail);
}

function cbCardDetail(r, e) {
    var ret = e;
    ret.data.imgPrefix = IMG_PREFIX;
    console.log(ret);
    $('ons-page#card-detail div.page__content').html('');
    $('ons-page#card-detail div.page__content').append($.templates(r).render(ret.data, rdHelper));
}

function initAllList(status) {
    var obj = {
        pageIndex: 0,
        pageSize: 222,
        status: status
    };

    (function($status)  {
      promiseTmpl('GET', '/mobile-tmpl/ac-all-render.tmpl' ,[URL_BUYER_ALL_ORDER, encodeQuery(obj)].join('?'), null, function(r, e){
        var ret = e;
        ret.imgPrefix = IMG_PREFIX;
        ret.data.status = $status;
        copyData = ret;
        if ($status === -1) {
            $('ons-page#ac-all div.page__content').html('');
            if(ret.data.length === 0){
                $('ons-page#ac-all div.page__content').append('<ons-card class="nothing-card">暂无记录</ons-card>');
            }else{
                $('ons-page#ac-all div.page__content').append($.templates(r).render(ret, rdHelper));
            }
        } else if ($status === 0) {
            $('ons-page#ac-operate div.page__content').html('');
            if(ret.data.length === 0){
                $('ons-page#ac-operate div.page__content').append('<ons-card class="nothing-card">暂无记录</ons-card>');
            }else {
                $('ons-page#ac-operate div.page__content').append($.templates(r).render(ret, rdHelper));
            }
        } else if ($status === 10) {
            $('ons-page#ac-deliver div.page__content').html('');
            if(ret.data.length === 0){
                $('ons-page#ac-deliver div.page__content').append('<ons-card class="nothing-card">暂无记录</ons-card>');
            }else {
                $('ons-page#ac-deliver div.page__content').append($.templates(r).render(ret, rdHelper));
            }
        } else if ($status === 20) {
            $('ons-page#ac-comment div.page__content').html('');
            if(ret.data.length === 0){
                $('ons-page#ac-comment div.page__content').append('<ons-card class="nothing-card">暂无记录</ons-card>');
            }else {
                $('ons-page#ac-comment div.page__content').append($.templates(r).render(ret, rdHelper));
            }
        } else if ($status === 30) {
            $('ons-page#ac-check div.page__content').html('');
            if(ret.data.length === 0){
                $('ons-page#ac-check div.page__content').append('<ons-card class="nothing-card">暂无记录</ons-card>');
            }else {
                $('ons-page#ac-check div.page__content').append($.templates(r).render(ret, rdHelper));
            }
        } else if ($status === 70) {
            $('ons-page#ac-complete div.page__content').html('');
            if(ret.data.length === 0){
                $('ons-page#ac-complete div.page__content').append('<ons-card class="nothing-card">暂无记录</ons-card>');
            }else {
                $('ons-page#ac-complete div.page__content').append($.templates(r).render(ret, rdHelper));
            }
        };

      })
    })(status)
}